<template>
    <div class="header">
        <div class="back" @click="router.go(-1)">
            返回
            <el-icon size="24">
                <ArrowRight />
            </el-icon>
        </div>
        <el-input v-model="title" class="title" placeholder="请输入标题" maxlength="50" show-word-limit size="large" />
        <div class="feature">
            <!-- <span class="tips">文章将自动保存至草稿箱</span>
            <el-button type="primary" plain size="large">草稿箱</el-button> -->
            <el-button type="primary" size="large" @click="handleIssue">发布</el-button>
        </div>
    </div>
    <div style="border: 1px solid #dcdfe6">
        <Toolbar style="border-bottom: 1px solid #dcdfe6" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="mode" />
        <Editor style="height: 80vh; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
            @onCreated="handleCreated" @onChange="handleChange" />
    </div>
    <el-dialog v-model="dialogVisible" title="发布文章" width="500" :before-close="handleClose">
        <el-form style="max-width: 600px" :model="form" status-icon label-width="auto" class="demo-ruleForm">
            <el-form-item label="类型" :rules="[
            {
                required: true,
                message: '请选择类型',
                trigger: 'blur',
            },
        ]">
                <el-radio-group v-model="form.type">
                    <el-radio-button label="代码人生" :value="1" />
                    <el-radio-button label="生活日常" :value="2" />
                    <el-radio-button label="小说畅想" :value="3" />
                    <el-radio-button label="其他" :value="4" />
                </el-radio-group>
            </el-form-item>
            <el-form-item label="类型" :rules="[
            {
                required: true,
                message: '请选择类型',
                trigger: 'blur',
            },
        ]">
                <el-radio-group v-model="form.isPrivate">
                    <el-radio-button label="私人" :value="0" />
                    <el-radio-button label="公开" :value="1" />
                </el-radio-group>
            </el-form-item>
            <el-form-item label="封面" :rules="[
            {
                required: true,
                message: '请选择封面',
                trigger: 'blur',
            },
        ]">
                <el-upload class="avatar-uploader" :headers="{
            authorization: token
        }" action="/api/document/uploadImage" name="image" :show-file-list="false" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="form.cover" :src="form.cover" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirm">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted, inject, type Ref } from 'vue'
const http: any = inject('http');
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { IEditorConfig, IDomEditor } from '@wangeditor/editor';
import { ElMessage, ElMessageBox, type FormInstance, type UploadProps } from 'element-plus';
import { useRouter, useRoute } from 'vue-router'
const router = useRouter();
const route = useRoute();

interface IResultModal {
    code: number;
    msg: string;
}

interface IDataModal {
    id: string;
    title: string;
    author: string;
    content: string;
    cover: string;
    type: number;
    status: number;
    createTime: string;
    cDate: string;
}
interface IResultModal2 {
    code: number;
    data: IDataModal[];
    msg: string;
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('');
const title = ref('');
const mode = ref('default');
const dialogVisible = ref(false)
const form = ref({
    type: 1,
    cover: '',
    isPrivate: 1
})

const loading = ref(false);
const content: Ref<IDataModal | null> = ref(null);
const token = ref(window.localStorage.getItem('token') || '');

const handleClose = (done: () => void) => {
    ElMessageBox.confirm('Are you sure to close this dialog?')
        .then(() => {
            done()
        })
        .catch(() => {
            // catch error
        })
}

const getBlogData = () => {
    http.post('/api/article/getArticle', {
        id: route.query.id
    }).then((res: IResultModal2) => {
        loading.value = false;
        if (res.code === 1) {
            valueHtml.value = res.data[0].content;
            title.value = res.data[0].title;
            form.value.cover = res.data[0].cover;
            form.value.type = res.data[0].type;
        }
    })
}

// 模拟 ajax 异步获取内容
onMounted(() => {
    // setTimeout(() => {
    //     valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    // }, 1500)
    if (route.query.type && route.query.type === 'edit') {
        getBlogData();
    }
})

const toolbarConfig = {}
// 初始化 MENU_CONF 属性
const editorConfig: Partial<IEditorConfig> = {  // TS 语法
    // const editorConfig = {                       // JS 语法
    MENU_CONF: {}
}

// 修改 uploadImage 菜单配置
editorConfig.MENU_CONF['uploadImage'] = {
    server: '/api/document/uploadImage',
    fieldName: 'image',
    headers: {
        authorization: window.localStorage.getItem('token')
    },
}

editorConfig.MENU_CONF['uploadVideo'] = {
    server: '/api/document/uploadVideo',
    fieldName: 'video',
    maxFileSize: 5000 * 1024 * 1024, // 5G
    headers: {
        authorization: window.localStorage.getItem('token')
    },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: IDomEditor) => {
    editorRef.value = editor
    console.log('created', editor)
}
const handleChange = (editor: IDomEditor) => {
    console.log('change:', editor.children)
    console.log(valueHtml.value);

}

const handleIssue = () => {
    if (!title.value && valueHtml.value) {
        return ElMessage.error('请添加标题或者文章内容');
    }
    dialogVisible.value = true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response);

    form.value.cover = response.data.url;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //   if (rawFile.type !== 'image/jpeg') {
    //     ElMessage.error('Avatar picture must be JPG format!')
    //     return false
    //   } else 
    if (rawFile.size / 1024 / 1024 > 20) {
        ElMessage.error('Avatar picture size can not exceed 20MB!')
        return false
    }
    return true
}

const handleConfirm = () => {
    loading.value = true;
    if (route.query.type && route.query.type === 'edit') {
        http.post('/api/article/editArticle', {
            id: route.query.id,
            title: title.value,
            content: valueHtml.value,
            type: form.value.type,
            cover: form.value.cover,
            author: 'TE',
            status: 2,
        }).then((res: IResultModal) => {
            if (res.code === 1) {
                loading.value = false;
                ElMessage.success('修改成功');
                router.push('/blog');
            }
        })
    } else {
        http.post('/api/article/saveArticle', {
            title: title.value,
            content: valueHtml.value,
            type: form.value.type,
            cover: form.value.cover,
            author: 'TE',
            status: 2,
        }).then((res: IResultModal) => {
            if (res.code === 1) {
                loading.value = false;
                ElMessage.success('发表成功');
                router.push('/blog');
            }
        })
    }

    return;

}
</script>
<style scoped>
.header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.header .back {
    line-height: 100%;
    display: flex;
    align-items: center;
    cursor: pointer;
    padding-right: 20px;
    color: #409eff;
    font-size: 17px;
}

.header .feature {
    flex: 1;
    text-align: right;
}

.header .feature .tips {
    margin: 0 10px;
    font-size: 14px;
    white-space: nowrap;
    color: #c9cdd4;
    cursor: default;
}

.header .title {
    line-height: 100%;
    display: flex;
    align-items: center;
    width: 70%;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.wang-editor .w-e-text-container p {
    line-height: 2;
    /* 设置为2倍行高 */
}
</style>